package com.njtoyo.taxi.admin.utils.private_number;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.njtoyo.taxi.admin.utils.private_number.report.DriverApplyPrivateCallWrapper;
import com.njtoyo.taxi.admin.utils.private_number.report.PrivateNumberAesHelper;
import jodd.json.JsonObject;
import jodd.json.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.springframework.stereotype.Component;
import weixin.popular.util.MapUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @author Dell
 * @date 2023/4/9 4:06 PM
 */
@Slf4j
public class PrivateNumberClient {

    //private static final String APP_KEY = "HBVJSKJT_0001";

    private static final String APP_KEY = "SLST";

    //private static final String APP_SECRET = "n$zMjzts6ey7SCNjz2zUyakJWCUM@Loz";

    public static final String APP_SECRET = "av5e6WPCjHegWsDm";

    private static final String REMOTE_URL = "http://north.spn.caihcom.com:9101/spn/secure";

    private static final String APP_MODE_CODE = "mode101";

    private static final String PLATFORM_MODE_CODE = "mode102";

    public static PrivateBindResult bindMobileNumber(String relationMobile, String callerMobile, String calleeMobile, String expire) {
        String url = StrUtil.format("{}/v2/axb/{}",REMOTE_URL,APP_MODE_CODE);
        Date now = new Date();
        Map<String,String> body = new HashMap<>();
        String requestId = String.valueOf(IdUtil.createSnowflake(1L,1L).nextId());
        body.put("requestId",requestId);
        body.put("telA",callerMobile);
        body.put("telX",relationMobile);
        body.put("telB",calleeMobile);
        body.put("subts",formatDate(now,"yyyyMMddHHmmss"));
        body.put("anucode","1,2,3");
        body.put("expiration",expire);
        Map<String,String> headers = new HashMap<>();
        headers.put("ts",formatDate(now,"yyyyMMddHHmmssSSS"));
        headers.put("appkey", APP_KEY);
        Map<String,String> toEncrypt = new HashMap<>();
        toEncrypt.putAll(body);
        toEncrypt.putAll(headers);
        String msgDigest = getMsgDigest(toEncrypt);
        headers.put("msgdgt",msgDigest);
        HttpResponse response = HttpUtil.createPost(url).addHeaders(headers).body(Json.toJson(body)).execute();
        log.info("bindMobileNumber response : {}",response.body());
        PrivateBindResult bindResult = new PrivateBindResult();
        bindResult.setSuccess(false);
        if (!response.isOk()) {
            return bindResult;
        }
        JsonObject result = JsonParser.create().parseAsJsonObject(response.body());
        if (result.getInteger("code") != 0) {
            log.error("PrivateNumberClient 请求失败 response: {}",result);
            return bindResult;
        }
        JsonObject data = result.getJsonObject("data");
        bindResult.setSubId(data.getString("subid"));
        bindResult.setTelX(data.getString("telX"));
        bindResult.setSuccess(true);
        return bindResult;
    }

    public static boolean unbindMobileNumber(String subid) {
        Date now = new Date();
        String url = StrUtil.format("{}/v2/axb/{}",REMOTE_URL,subid);
        Map<String,String> headers = new HashMap<>();
        headers.put("appkey", APP_KEY);
        headers.put("ts",formatDate(now,"yyyyMMddHHmmssSSS"));
        Map<String,String> toEncrypt = new HashMap<>();
        toEncrypt.putAll(headers);
        String msgDigest = getMsgDigest(toEncrypt);
        headers.put("msgdgt",msgDigest);
        HttpResponse response = HttpUtil.createRequest(Method.DELETE,url).addHeaders(headers).execute();
        if (!response.isOk()) {
            log.error("unbindMobileNumber 请求失败 response:{}",response);
            return false;
        }
        JsonObject result = JsonParser.create().parseAsJsonObject(response.body());
        if (result.getInteger("code") != 0) {
            log.error("unbindMobileNumber 请求失败 response:{}",result);
            return false;
        }
        return true;
    }

    public void queryBindStateBySubId(String subid) {
        Date now = new Date();
        String url = StrUtil.format("{}/v2/axb/subid/{}",REMOTE_URL,subid);
        Map<String,String> headers = new HashMap<>();
        headers.put("appkey", APP_KEY);
        headers.put("ts",formatDate(now,"yyyyMMddHHmmssSSS"));
        Map<String, String> toEncrypt = new HashMap<>(headers);
        String msgDigest = getMsgDigest(toEncrypt);
        headers.put("msgdgt",msgDigest);
        HttpResponse response = HttpUtil.createRequest(Method.GET,url).addHeaders(headers).execute();
        log.info("query bind state by subId : {}",response.body());
    }

    public static String getMsgDigest(Map<String,String> params) {
        Map<String,String> ordered = MapUtil.order(params);
        StringJoiner joiner = new StringJoiner("");
        ordered.forEach((k,v) -> joiner.add(k).add(v));
        return SecureUtil.md5(APP_SECRET+joiner).toUpperCase();
    }

    public static String formatDate(Date date,String format) {
        return DateUtil.format(date,format);
    }


    public static Pair<Boolean,String> sendDriverApplyPrivateCall(DriverApplyPrivateCallWrapper driverApplyPrivateCallWrapper) {
        String url = "http://120.133.16.101/ops/intensive/actuality/report";
        Date now = new Date();
        Map<String,String> body = new HashMap<>();
        String requestId = IdUtil.objectId();
        body.put("requestId",requestId);
        body.put("phoneNumber", PrivateNumberAesHelper.encryptBase64(driverApplyPrivateCallWrapper.getDriverNumber()));
        body.put("numberType","0");
        body.put("personnelType","0");
        body.put("personName",PrivateNumberAesHelper.encryptBase64(driverApplyPrivateCallWrapper.getDriverName()));
        body.put("idType","0");
        body.put("idNumber",PrivateNumberAesHelper.encryptBase64(driverApplyPrivateCallWrapper.getIdNumber()));
        body.put("subts",formatDate(now,"yyyyMMddHHmmss"));
        Map<String,String> headers = new HashMap<>();
        headers.put("ts",formatDate(now,"yyyyMMddHHmmssSSS"));
        headers.put("appkey", APP_KEY);
        Map<String,String> toEncrypt = new HashMap<>();
        toEncrypt.putAll(body);
        toEncrypt.putAll(headers);
        String msgDigest = getMsgDigest(toEncrypt);
        headers.put("msgdgt",msgDigest);
//        body.put("idPhotoFront",PrivateNumberAesHelper.encryptBase64(driverApplyPrivateCallWrapper.getIdPhotoFront()));
//        body.put("idPhotoBack",PrivateNumberAesHelper.encryptBase64(driverApplyPrivateCallWrapper.getIdPhotoBack()));
        body.put("scenePhoto",PrivateNumberAesHelper.encryptBase64(driverApplyPrivateCallWrapper.getScenePhoto()));
        HttpResponse response = HttpUtil.createPost(url).addHeaders(headers).body(Json.toJson(body)).execute();
        log.info("driver apply private call response : {}",response.body());
        JsonObject result = JsonParser.create().parseAsJsonObject(response.body());
        if (result.getInteger("code") != 0) {
            log.info("PrivateNumberClient driver apply private call 请求失败 response: {}",result);
            return new Pair<>(false,result.getString("message"));
        }
        return new Pair<>(true,"success");
    }

}
